package com.xiangxiao.rpan.storage.download.url;

import com.xiangxiao.rpan.storage.core.DownloadFileTool;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2023/12/1 17:40
 */
@Component(value = "downloadFileURL")
public class DownloadFileURL implements DownloadFileTool {
  @Override
  public void readStreamToFile(String path, HttpServletResponse response) {
    ServletOutputStream out = null;
    try {
      // 与服务器建立连接
      URL url = new URL(path);
      URLConnection conn = url.openConnection();
      InputStream inputStream = conn.getInputStream();
      try {
        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
        response.setContentType("multipart/form-data");
      } catch (Exception e){
        e.printStackTrace();
      }
      out = response.getOutputStream();
      // 读取文件流
      int len = 0;
      byte[] buffer = new byte[1024 * 10];
      while ((len = inputStream.read(buffer)) != -1) {
        out.write(buffer, 0, len);
      }
      out.flush();
    } catch (Exception e){
      e.printStackTrace();
    }
  }

  @Override
  public String convertMuitlFileToStream(MultipartFile multipartFile, Integer chunkNumber, Integer totalChunks, long blockSize) {
    return null;
  }
}
